# 1.14 对不原生支持比较操作的对象排序
# 例:
class User:
    def __init__(self,uid):
        self.uid = uid
    def __repr__(self):
        return 'User({})'.format(self.uid)
users = [User(233),User(99),User(211)]

#  方案 1 是用lambda表达式
sorted_user = sorted(users, key=lambda u:u.uid)
print(sorted_user)

# 方案 2 用 operator.attrgetter() 方法 , 类似于针对字典的itemgetter
from operator import attrgetter
sorted_user2 = sorted(users,key=attrgetter('uid'))
print(sorted_user2)

# 1.15 根据字段将记录分组, 比如想用日期来分组迭代数据
# 解决方案 使用itertools.groupby() 函数对数据进行分组
rows = [
    {'address': 'ningbo 11#', 'date': '2018-10-21'},
    {'address': 'ningbo 123#', 'date': '2018-10-20'},
    {'address': 'ningbo 77#', 'date': '2018-10-20'},
    {'address': 'ningbo 55#', 'date': '2018-10-22'},
    {'address': 'ningbo 44#', 'date': '2018-10-22'},
    {'address': 'ningbo 34#', 'date': '2018-10-21'},
    {'address': 'ningbo 36#', 'date': '2018-10-22'},
    {'address': 'ningbo 87#', 'date': '2018-10-21'},
    {'address': 'ningbo 66#', 'date': '2018-10-21'},
    {'address': 'ningbo 54#', 'date': '2018-10-22'},
    {'address': 'ningbo 33#', 'date': '2018-10-21'},
    {'address': 'ningbo 25#', 'date': '2018-10-24'},
]

# 先排序,再分组
from operator import itemgetter
from itertools import groupby
rows.sort(key=itemgetter('date'))
# groupby 会产生一个值和一个子迭代器(该分组下的所有记录)
for date, items in groupby(rows,key=itemgetter('date')):
    print(date)
    for i in items:
        print('  ', i)
#如果是简单的根据日期分组到一起, 可以利用defaultdict()构建一个一键多字典(详见1.6):
from collections import defaultdict
rows_by_date = defaultdict(list)
for row in rows:
    rows_by_date[row['date']].append(row)
print(rows_by_date)
for r in rows_by_date['2018-10-21']:
    print(r)
